/**
 *
 * @type {exports}
 */
var dbUtils = require('./database.dao.utils');
var fs = require('fs');

function typeOfValue(value) {
  return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}
function transferTreeToArray(jsonTree) {
  var jsonArr = [];
  if (typeOfValue(jsonTree) === 'array') {
    jsonTree.forEach(function (el) {
      Array.prototype.push.apply(jsonArr, transferTreeToArray(el));
    });
  } else if (typeOfValue(jsonTree) === 'object') {
    jsonArr.push(jsonTree);
    jsonTree['child'] ? Array.prototype.push.apply(jsonArr, transferTreeToArray(jsonTree['child'])) : '';
  }
  return jsonArr;
}

function UserFavorite(name, pass) {
  this.user = {
    name: name, pass: pass, logined: false
  }
}

UserFavorite.prototype.login = function (callback) {
  dbUtils.find({name: this.user.name, pwd: this.user.pass}, {name: 1, pwd: 1}, function (err, data) {
    console.log(err, data);
    //err ? callback(err) : callback(err, data);
  });
};

UserFavorite.prototype.logined = function () {
  return this.user.logined;
};

UserFavorite.prototype.favorite = function (callback) {
  var me = this;
  dbUtils.find(function (err, data) {
    callback(err, data ? transferTreeToArray(JSON.parse(data).bookmarks.child) : data);
  });
};

module.exports = UserFavorite;
